package com.warom.sdg.ui.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import com.warom.sdg.R;
import com.warom.sdg.service.PlcDataService;
import com.warom.sdg.util.LogUtils;

import com.warom.sdg.websocket.WebSocketService;
import com.warom.sdg.webview.WebViewWrapper;
import com.warom.sdg.webview.jsinterface.WebViewJsInterface;
import com.warom.sdg.webview.jsinterface.WebViewJsVentilationConfigInterface;


public class MainActivity extends AppCompatActivity  {
    private static final String TAG = "MainActivity";
    private WebViewWrapper webViewWrapper;
    private FloatingActionButton fabSendMessage;
    
    // private static final String HTML_FILE_PATH = "http://222.222.25.198:19304/app/";
    // 目标URL - 使用assets目录下的HTML文件
    private static final String HTML_FILE_PATH = "file:///android_asset/page/index.html";
    
    // 固定发送给H5的消息
    private static final String FIXED_MESSAGE = "来自Android的固定消息";
    
    // 缓存模式标志
    private boolean useCacheMode = false;
    
    // 权限请求码
    private static final int PERMISSION_REQUEST_CODE = 101;
    private static final int MANAGE_STORAGE_REQUEST_CODE = 102;

    // 控制退出应用时是否停止服务
    private boolean stopServiceOnExit = false;

    // 添加PLC数据服务的绑定相关变量
    private PlcDataService plcDataService;
    private boolean serviceBound = false;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            PlcDataService.PlcServiceBinder binder = (PlcDataService.PlcServiceBinder) service;
            plcDataService = binder.getService();
            serviceBound = true;
            
            // 设置服务到WebSocketService
            if (webSocketServiceBound && webSocketService != null) {
                webSocketService.setPlcDataService(plcDataService);
                Log.d(TAG, "已将PlcDataService设置到WebSocketService");
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            serviceBound = false;
            plcDataService = null;
            Log.d(TAG, "与PLC数据服务的连接已断开");
        }
    };

    // WebSocket服务
    private WebSocketService webSocketService;
    private boolean webSocketServiceBound = false;
    
    // WebSocket服务连接
    private ServiceConnection webSocketServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            WebSocketService.WebSocketBinder binder = (WebSocketService.WebSocketBinder) service;
            webSocketService = binder.getService();
            webSocketServiceBound = true;
            
            // 如果PLC服务已经绑定，则设置到WebSocketService
            if (serviceBound && plcDataService != null) {
                webSocketService.setPlcDataService(plcDataService);
                Log.d(TAG, "已将PlcDataService设置到WebSocketService");
            }
            
            Log.d(TAG, "已连接到WebSocket服务");
        }
        
        @Override
        public void onServiceDisconnected(ComponentName name) {
            webSocketServiceBound = false;
            webSocketService = null;
            Log.d(TAG, "与WebSocket服务的连接已断开");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_demo);
        
        // 记录活动创建
        LogUtils.logOperation("MainActivity", "onCreate", "应用界面初始化");
        
        // 请求必要的权限
        requestAppPermissions();
        
        // 隐藏ActionBar，实现全屏效果
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        
        // 初始化视图
        webViewWrapper = findViewById(R.id.webview_wrapper);
        fabSendMessage = findViewById(R.id.fab_send_message);

        // 在 WebViewWrapper 中注册新的接口
        //webViewWrapper.addJavascriptInterface(new WebViewJsVentilationConfigInterface(this), "VentilationConfig");
        
        // 清除WebView缓存
        // clearWebViewCache();
        
        // 设置JavaScript交互回调
//        webViewWrapper.setJsCallback(this);
        
        // 打印URL以便日志查看
        Log.d(TAG, "正在加载URL: " + HTML_FILE_PATH);
        LogUtils.logOperation("WebView", "加载", "URL: " + HTML_FILE_PATH);
        
        // 显示Toast提示当前加载的URL
        //Toast.makeText(this, "正在加载: " + HTML_FILE_PATH, Toast.LENGTH_LONG).show();
        
        // 加载HTML文件，不使用缓存
        webViewWrapper.loadUrl(HTML_FILE_PATH, useCacheMode);
        
        // 启用WebView调试
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }
        
        // 设置浮动按钮点击事件
        fabSendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到ModbusDemoActivity2
                Intent intent = new Intent(MainActivity.this, ModbusDemoActivity2.class);
                startActivity(intent);
            }
        });
        
        // 启动PLC数据采集服务
        startPlcDataService();
        // 启动并绑定WebSocket服务
        // startWebSocketService();
        // bindWebSocketService();
    }
    
    /**
     * 启动PLC数据采集服务
     */
    private void startPlcDataService() {
        try {
            Intent serviceIntent = new Intent(this, PlcDataService.class);
            startService(serviceIntent);
            // 绑定服务以获取服务实例
            bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
            
            LogUtils.logOperation("服务", "启动", "PLC数据采集服务已启动");
            Log.d(TAG, "PLC数据采集服务已启动");
        } catch (Exception e) {
            LogUtils.logError("服务", "启动PLC数据采集服务失败", e);
            Log.e(TAG, "启动PLC数据采集服务失败", e);
        }
    }
    
    /**
     * 停止PLC数据采集服务
     */
    private void stopPlcDataService() {
        try {
            Intent serviceIntent = new Intent(this, PlcDataService.class);
            stopService(serviceIntent);
            LogUtils.logOperation("服务", "停止", "PLC数据采集服务已停止");
            Log.d(TAG, "PLC数据采集服务已停止");
        } catch (Exception e) {
            LogUtils.logError("服务", "停止PLC数据采集服务失败", e);
            Log.e(TAG, "停止PLC数据采集服务失败", e);
        }
    }
    
    /**
     * 请求应用所需权限
     */
    private void requestAppPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11及以上使用MANAGE_EXTERNAL_STORAGE权限
            if (!Environment.isExternalStorageManager()) {
                Toast.makeText(this, "需要获取所有文件访问权限以保存日志", Toast.LENGTH_LONG).show();
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, MANAGE_STORAGE_REQUEST_CODE);
                } catch (Exception e) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    startActivityForResult(intent, MANAGE_STORAGE_REQUEST_CODE);
                }
            }
        } else {
            // Android 10及以下使用存储权限
            String[] permissions = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
            
            boolean needRequestPermission = false;
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    needRequestPermission = true;
                    break;
                }
            }
            
            if (needRequestPermission) {
                ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
            }
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            
            if (allGranted) {
                LogUtils.logOperation("权限", "授权成功", "存储权限已获取");
                Toast.makeText(this, "存储权限已授予，日志将保存到SD卡", Toast.LENGTH_SHORT).show();
            } else {
                LogUtils.logOperation("权限", "授权失败", "存储权限被拒绝");
                Toast.makeText(this, "存储权限被拒绝，日志功能可能受限", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == MANAGE_STORAGE_REQUEST_CODE) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (Environment.isExternalStorageManager()) {
                    LogUtils.logOperation("权限", "授权成功", "文件管理权限已获取");
                    Toast.makeText(this, "文件管理权限已授予，日志将保存到SD卡", Toast.LENGTH_SHORT).show();
                } else {
                    LogUtils.logOperation("权限", "授权失败", "文件管理权限被拒绝");
                    Toast.makeText(this, "文件管理权限被拒绝，日志功能可能受限", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    
    /**
     * 清除WebView的所有缓存
     */
    private void clearWebViewCache() {
        // 清除所有Cookie
        android.webkit.CookieManager.getInstance().removeAllCookies(null);
        android.webkit.CookieManager.getInstance().flush();
        
        // 清除缓存数据库
        deleteDatabase("webview.db");
        deleteDatabase("webviewCache.db");
        
        // 清除所有WebView数据
        WebView webView = webViewWrapper.getWebView();
        if (webView != null) {
            webView.clearCache(true);
            webView.clearHistory();
            webView.clearFormData();
            
            // 清除存储
            webView.clearSslPreferences();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                android.webkit.WebStorage.getInstance().deleteAllData();
            }
        }
        
        Log.d(TAG, "WebView缓存已清除");
        LogUtils.logOperation("WebView", "清除缓存", "清除了所有WebView缓存数据");
    }
    

    @Override
    protected void onResume() {
        super.onResume();
        webViewWrapper.onResume();
        LogUtils.logOperation("MainActivity", "onResume", "页面恢复");
        
        // 打印当前URL当前状态
        Log.d(TAG, "WebView当前URL: " + webViewWrapper.getUrl());
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        webViewWrapper.onPause();
        LogUtils.logOperation("MainActivity", "onPause", "页面暂停");
    }
    
    @Override
    protected void onDestroy() {
        // 停止PLC数据采集服务（如果需要）
        if (stopServiceOnExit) {
            stopPlcDataService();
            LogUtils.logOperation("服务", "退出时停止", "PLC数据采集服务已随应用退出而停止");
        } else {
            LogUtils.logOperation("服务", "后台保持", "PLC数据采集服务将在后台继续运行");
        }
        
        // 解绑服务
        if (serviceBound) {
            unbindService(serviceConnection);
            serviceBound = false;
        }
        
        // 解绑WebSocket服务
        if (webSocketServiceBound) {
            unbindService(webSocketServiceConnection);
            webSocketServiceBound = false;
        }
        
        webViewWrapper.onDestroy();
        LogUtils.logOperation("MainActivity", "onDestroy", "页面销毁");
        super.onDestroy();
    }

    /**
     * 绑定WebSocket服务
     */
    private void bindWebSocketService() {
        Intent intent = new Intent(this, WebSocketService.class);
        bindService(intent, webSocketServiceConnection, Context.BIND_AUTO_CREATE);
    }
    
    /**
     * 启动WebSocket服务
     */
    private void startWebSocketService() {
        try {
            Intent intent = new Intent(this, WebSocketService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(intent);
            } else {
                startService(intent);
            }
            LogUtils.logOperation("服务", "启动", "WebSocket服务已启动");
            Log.d(TAG, "WebSocket服务已启动");
        } catch (Exception e) {
            LogUtils.logError("服务", "启动WebSocket服务失败", e);
            Log.e(TAG, "启动WebSocket服务失败", e);
        }
    }
} 